package org.msfj.admin.org.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.msfj.admin.model.*;
import org.msfj.admin.org.mapper.DeptMapper;
import org.msfj.admin.org.mapper.MenuMapper;
import org.msfj.admin.org.mapper.UserMapper;
import org.msfj.admin.org.mapper.UserRoleMapper;
import org.msfj.admin.org.service.UserService;
import org.msfj.admin.vo.DeptVo;
import org.msfj.admin.vo.UserVo;
import org.msfj.common.annotation.Constants;
import org.msfj.common.base.BaseServiceImpl;
import org.msfj.common.enums.Enable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @Description: 系统用户信息service实现类
 * @Author: like
 * @Email: like@deyatong.com
 * @Date: 2017-08-10 17:30:20
 * @Version: 1.0
 * @Created in idea by autoCode
 */

@Service
@CacheConfig(cacheNames = Constants.CACHE_NAMESPACE + "user")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 根据条件分页查询系统用户信息列表
     *
     * @param userVo
     * @param page   当前第几页
     * @param rows   每页多少条记录
     * @return PageInfo<User>
     */
    @Override
    //@Cacheable
    public PageInfo<UserVo> getByUser(UserVo userVo, int page, int rows) {
        Example example = createExample(userVo);
        PageHelper.startPage(page, rows);
        List<User> user = new ArrayList<>();
        if (ObjectUtil.isNotNull(example)) {
            user = super.getByExample(example);
        }
        PageInfo userVoPageInfo = new PageInfo(user);
        userVoPageInfo.setList(setOtherProperties(user));
        return userVoPageInfo;
    }

    /**
     * 根据条件查询所有系统用户信息对象列表
     *
     * @param userVo
     * @return List<User>
     */
    @Override
    //@Cacheable
    public List<UserVo> getAllUser(UserVo userVo) {
        Example example = createExample(userVo);
        if (ObjectUtil.isNull(example)) {
            return null;
        }
        List<UserVo> userVoList = setOtherProperties(super.getByExample(example));
        return userVoList;
    }

    private Example createExample(UserVo userVo) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("enable", Enable.ENABLE.getCode());
        if (ObjectUtil.isNotNull(userVo)) {
            if (StrUtil.isNotBlank(userVo.getAccount())) {
                criteria.andEqualTo("account", userVo.getAccount());
            }
            if (StrUtil.isNotBlank(userVo.getName())) {
                criteria.andLike("name", "%".concat(userVo.getName()).concat("%"));
            }
            if (ObjectUtil.isNotNull(userVo.getDeptId())) {
//                Dept dept = deptMapper.selectByPrimaryKey(userVo.getDeptId());
                criteria.andEqualTo("deptId", userVo.getDeptId());
            }
            if (ObjectUtil.isNotNull(userVo.getId())) {
                criteria.andEqualTo("id", userVo.getId());
            }
            if (StrUtil.isNotBlank(userVo.getUserDepartments())) {
                criteria.andIn("deptId", Arrays.asList(userVo.getUserDepartments().split(",")));
            }
        }
        return example;
    }

    /**
     * 设置vo的其他属性属性
     *
     * @param user
     * @return DepartmentVo
     */
    @Override
    //@Cacheable
    public UserVo setOtherProperties(User user) {
        if (user == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        DeptVo sysdeptVo = new DeptVo();
        BeanUtils.copyProperties(user, userVo);
        Dept dept = deptMapper.selectByPrimaryKey(userVo.getDeptId());
        BeanUtils.copyProperties(dept, sysdeptVo);
        if (ObjectUtil.isNotNull(dept)) {
            userVo.setDeptVo(sysdeptVo);
        }
        List<Menu> menus = menuMapper.selectAllMenuByUserId(user.getId());
        List<String> permissions = CollectionUtil.newArrayList();
        for (Menu menu : menus) {
            permissions.add(menu.getPermission());
        }
        userVo.setPermissions(permissions);
        return userVo;
    }

    /**
     * 设置vo的其他属性属性
     *
     * @param users
     * @return List<UserVo>
     */
    @Override
    //@Cacheable
    public List<UserVo> setOtherProperties(List<User> users) {
//        List<Dept> depts = deptMapper.selectAll();
        List<UserVo> userVos = new ArrayList<>();
        Map<String, Dept> deptMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(users)) {
            for (User user : users) {
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                DeptVo deptVo = new DeptVo();
                Dept dept = deptMap.get(user.getDeptId());
                if (dept == null) {
                    dept = this.deptMapper.selectByPrimaryKey(user.getDeptId());
                    deptMap.put(user.getDeptId(), dept);
                }
                if (dept != null) {
                    BeanUtils.copyProperties(dept, deptVo);
                    userVo.setDeptVo(deptVo);
                }
                userVos.add(userVo);
            }
        }
        return userVos;
    }

    /**
     * 查询用户表拼接部门名称与用户，返回Map
     *
     * @param userVo
     * @return
     */
    @Override
    //@Cacheable
    public Map<String, List<UserVo>> getUsersByDeptIds(UserVo userVo) {
        Map<String, List<UserVo>> deptNameAndUserName = new HashMap<>();
        List<UserVo> userVos = this.getAllUser(userVo);
        if (CollectionUtil.isNotEmpty(userVos)) {
            for (UserVo userVo2 : userVos) {
                String deptName;
                if (ObjectUtil.isNotNull(userVo2.getDeptVo())) {
                    deptName = userVo2.getDeptVo().getName();
                } else {
                    deptName = "";
                }
                List<UserVo> userVos1 = deptNameAndUserName.get(deptName);
                if (userVos1 == null) {
                    userVos1 = new ArrayList<>();
                    deptNameAndUserName.put(deptName, userVos1);
                }
                userVos1.add(userVo2);
            }
        }
        return deptNameAndUserName;
    }

    /**
     * 删除用户同时删除用户角色关联信息
     *
     * @param ids
     * @param user
     */
    @Override
    @Transactional
    public void delAllByIds(String[] ids, User user) {
        if (ArrayUtil.isNotEmpty(ids)) {
            Example example = new Example(UserRole.class);
            example.createCriteria().andIn("id", Arrays.asList(ids));
            userRoleMapper.deleteByExample(example);
            super.delByIds(Arrays.asList(ids), user, Role.class, UserRole.class);
        }
    }

    @Override
    //@Cacheable
    public List<UserVo> getByIds(List<String> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {
            Example example = new Example(UserRole.class);
            example.createCriteria().andIn("id", ids).andEqualTo("enable", Enable.ENABLE.getCode());
            ;
            List<User> byExample = super.getByExample(example);
            return setOtherProperties(byExample);
        }
        return Collections.emptyList();
    }

    @Override
    //@Cacheable
    public List<UserVo> getAllUser() {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("enable", 1);
        example.orderBy("name");
        List<User> byExample = super.getByExample(example);
        return setOtherProperties(byExample);
    }

    @Override
    //@Cacheable
    public UserVo getUserByAccount(String account) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("enable", Enable.ENABLE.getCode()).andEqualTo("account", account);
        List<User> byExample = super.getByExample(example);
        if (CollectionUtil.isNotEmpty(byExample)) {
            return setOtherProperties(byExample.get(0));
        }
        return null;
    }

    @Override
    public UserVo getUserByEmpNo(String empNo) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("enable", Enable.ENABLE.getCode()).andEqualTo("empNo", empNo);
        List<User> byExample = getByExample(example);
        if (CollectionUtil.isNotEmpty(byExample)) {
            return setOtherProperties(byExample.get(0));
        }
        return null;
    }

    @Override
    //@Cacheable
    public Map<String, String> getUserNames(List<String> userId) {
        if (userId == null || userId.isEmpty()) {
            return Collections.EMPTY_MAP;
        }
        Example example = new Example(User.class);
        example.createCriteria().andIn("id", userId);
        List<User> users = this.userMapper.selectByExample(example);
        if (users != null) {
            Map<String, String> result = new HashMap<>();

            for (User user : users) {
                result.put(user.getId(), user.getName());
            }
            return result;
        }
        return Collections.EMPTY_MAP;
    }

    @Override
    public String encryptPassword(String rawPassword) {
        return new BCryptPasswordEncoder(Constants.PW_ENCORDER_SALT).encode(rawPassword);
    }
}
